package com.itpan.Controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.itpan.Entity.Product;
import com.itpan.Entity.PurchaseOrder;
import com.itpan.Entity.PurchaseOrderDetail;
import com.itpan.Service.ProductService;
import com.itpan.Service.PurchaseOrderDetailService;
import com.itpan.Service.PurchaseOrderService;
import com.itpan.Utils.EntityValidate;
import com.itpan.Utils.PurchaseOrderDetailExcelListener;
import com.itpan.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Api(value = "采购明细接口")
@RestController
@RequestMapping("/purchaseorderdetail")
public class PurchaseOrderDetailController {

    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private ProductService productService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private EntityValidate entityValidate;

    @Cacheable(value = "purchaseorderdetail",key = "'all'")
    @ApiOperation(value = "查询全部采购明细")
    @GetMapping("/all")
    public R<List<PurchaseOrderDetail>> getAll() {
        List<PurchaseOrderDetail> list = purchaseOrderDetailService.getall();
        return R.success(list);
    }

    @GetMapping("/getalltable")
    @ApiOperation(value = "下载全部带表格")
    public void getalltable(HttpServletResponse response) throws IOException {
        List<PurchaseOrderDetail> list = purchaseOrderDetailService.getall();
        setExcelRespProp(response, "采购明细表");
        EasyExcel.write(response.getOutputStream(), PurchaseOrderDetail.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("采购明细列表")
                .doWrite(list);
        response.getOutputStream().flush();
    }

    @Cacheable(value = "purchaseorderdetail",key = "#p0"+'-'+"#p1")
    @GetMapping("/allpage")
    @ApiOperation(value = "查询全部采购明细带分页")
    public R<List<PurchaseOrderDetail>> getAllPage(Integer page, Integer pageSize) {
        List<PurchaseOrderDetail> list = purchaseOrderDetailService.getallpage(page, pageSize);
        return R.success(list);
    }

    @PostMapping("/getbymutil")
    @ApiOperation(value = "模糊查询不带表格")
    public R<List<PurchaseOrderDetail>> getByMutil(@RequestBody PurchaseOrderDetail purchaseOrderDetail) {
        List<PurchaseOrderDetail> list = purchaseOrderDetailService.getByMutil(purchaseOrderDetail);
        return R.success(list);
    }

    @PostMapping("/getbymutiltable")
    @ApiOperation(value = "模糊查询带表格")
    public void getByMutilTable(@RequestBody PurchaseOrderDetail purchaseOrderDetail, HttpServletResponse response) throws IOException {
        List<PurchaseOrderDetail> list = purchaseOrderDetailService.getByMutil(purchaseOrderDetail);
        setExcelRespProp(response, "采购明细表");
        EasyExcel.write(response.getOutputStream(), PurchaseOrderDetail.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("采购明细列表")
                .doWrite(list);
        response.getOutputStream().flush();
    }

    @CacheEvict(value = "purchaseorderdetail",allEntries = true)
    @PostMapping("/addone")
    @ApiOperation(value = "新增一条采购明细")
    public R<String> addOne(@RequestBody PurchaseOrderDetail purchaseOrderDetail) {


        //先去判断对应的商品和采购主表是否存在，都存在才能添加
        if(!entityValidate.isValidateOfPurchaseOrderDetail(purchaseOrderDetail)){
            return R.error("信息填写错误");
        }

        //拿到商品
        Product po = productService.getById(purchaseOrderDetail.getProductID());

        //拿到主表
        PurchaseOrder pu=purchaseOrderService.getById(purchaseOrderDetail.getOrderID());

        if(!(po!=null&&pu!=null)) return R.error("输入的商品号或者订单号不存在");


        //如果都存在就继续执行操作

        purchaseOrderDetailService.saveOne(purchaseOrderDetail);
        return R.success("新增成功");
    }

/*
批量导入
 */
    @CacheEvict(value = "purchaseorderdetail",allEntries = true)
    @PostMapping("/addall")
    @ApiOperation(value = "批量导入采购明细记录")
    public R<String> addAll(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return R.error("文件不能为空");
        }
        EasyExcel.read(file.getInputStream(), PurchaseOrderDetail.class, new PurchaseOrderDetailExcelListener(purchaseOrderDetailService, entityValidate, purchaseOrderService, productService))  .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doRead();

        return R.success("批量导入成功");
    }

    /*
    更新
     */
    @CacheEvict(value = "purchaseorderdetail",allEntries = true)
    @PostMapping("/update")
    @ApiOperation(value = "更新采购明细")
    public R<String> update(@RequestBody PurchaseOrderDetail purchaseOrderDetail) {

        if(!entityValidate.isValidateOfPurchaseOrderDetail(purchaseOrderDetail)){
            return R.error("信息填写错误");
        }

        //先去判断对应的商品和采购主表是否存在，都存在才能添加

        //拿到商品
        Product po = productService.getById(purchaseOrderDetail.getProductID());

        //拿到主表
        PurchaseOrder pu=purchaseOrderService.getById(purchaseOrderDetail.getOrderID());

        if(!(po!=null&&pu!=null)) return R.error("输入的商品号或者订单号不存在");


        //如果都存在就继续执行操作

        purchaseOrderDetailService.update(purchaseOrderDetail);
        return R.success("更新成功");
    }


    @CacheEvict(value = "purchaseorderdetail",allEntries = true)
    @DeleteMapping("/delete")
    @ApiOperation(value = "根据采购明细ID删除记录")
    public R<String> deleteById(Long id) {
        purchaseOrderDetailService.delete(id);
        return R.success("删除成功");
    }

    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
    }
}
